import { Component } from 'react';
import { CDNURL } from './core';
import videoUpload from './videoUpload';

import './index.less';

class UploadVideo extends Component {
    state = {
        // playSrc: '',
    };

    componentDidMount() {
        const { success, remove } = this.props;

        this.updateData();
        videoUpload($(this.parent), {
            success: key => {
                success && success(key);
                this.updateVideoCover();
            },
            remove() {
                remove && remove();
            },
        });
    }

    componentDidUpdate() {
        this.updateData();
    }

    updateVideoCover() {
        const $parent = $(this.parent);
        const videoPoster = $parent.data('poster');
        $parent.find('.video-uploading').css('background-image', `url(${videoPoster})`);
    }

    getVideoInfo(key) {
        const newKey = key.slice(0, key.lastIndexOf('.'));

        return {
            videoCover: `${CDNURL}wpt_cover_${newKey}`,
            videoUrl: `${CDNURL}wpt_${newKey}`,
        };
    }

    // 更新数据
    updateData() {
        const $parent = $(this.parent);
        const { video } = this.props;
        let { videoCover, videoUrl } = this.props;
        if (!$parent.data('src') && videoUrl) {
            if (video && !videoCover) {
                const info = this.getVideoInfo(video);
                videoUrl = info.videoUrl;
                videoCover = info.videoCover;
            }
            const done = videoUrl ? 'done' : '';
            $parent
                .toggleClass('done', done)
                .data('cdn', CDNURL)
                .data('poster', videoCover)
                .data('src', videoUrl);
            // 更新cover
            this.updateVideoCover();
        }
    }

    render() {
        return <div className="video-upload-warp" ref={c => { this.parent = c; } } />;
    }
}

export default UploadVideo;
